import axios, { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { ApiResponse } from '@/types/commonType'

const request:AxiosInstance  = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 6000,
});
  /**
   * loading控制器
   * 请求拦截器
   */
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    if (!config.headers){
        return config
    }
    config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`
    config.headers["Content-Type"] = "application/json;charset=utf-8"
    return config;
})
/**
 * 响应拦截器
 */
request.interceptors.response.use(
    (res: AxiosResponse) => {
        const { data, status, statusText } = res;
        if (status === 200) return data ;
        //提示警告
        console.warn(statusText);
        return res;
    },
    (err: AxiosError) => {
        const { message } = err;
        //提示错误
        console.error(message);
        return Promise.reject(err);
    }
)

export default request

export const get = <T>(url: string, params?: {}): Promise<ApiResponse<T>> => {
    return request.get(url, { params });
}

export const post = <T>(url: string, data?: {}): Promise<ApiResponse<T>> => {
    return request.post(url, data);
}